package org.budo.graph.view.util;

import java.util.List;

import org.budo.support.slf4j.Slf4j;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;
import org.budo.support.spring.util.SpringUtil;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @author limingwei
 */
public class DruidDataSourceUtil {
    private static final Logger log = Slf4j.getLogger();

    private static List<DruidDataSource> _druidDataSourceList;

    public static List<DruidDataSource> getDruidDataSourceList() {
        if (null != _druidDataSourceList) {
            return _druidDataSourceList;
        }

        return _druidDataSourceList = findDruidDataSourceInApplicationContext();
    }

    private static List<DruidDataSource> findDruidDataSourceInApplicationContext() {
        BudoApplicationContextAware applicationContextAware = BudoApplicationContextAware.getInstance();
        if (null == applicationContextAware) {
            log.warn("#79 BudoApplicationContextAware is null");
            return null;
        }

        ApplicationContext applicationContext = applicationContextAware.getApplicationContext();
        if (null == applicationContext) {
            log.warn("#85 applicationContext is null, applicationContextAware=" + applicationContextAware);
            return null;
        }

        List<DruidDataSource> list = SpringUtil.getBeanListByType(applicationContext, DruidDataSource.class);
        if (null == list || list.isEmpty()) {
            log.warn("#91 druidDataSource is null, applicationContext=" + applicationContext);
            return null;
        }

        return list;
    }

    public static Integer druidMaxActive(ApplicationContext applicationContext) {
        String[] beanNames = applicationContext.getBeanNamesForType(DruidDataSource.class);
        if (null == beanNames) {
            return -1;
        }

        if (beanNames.length < 1) {
            return -2;
        }

        String beanName = beanNames[0];
        DruidDataSource druidDataSource = (DruidDataSource) applicationContext.getBean(beanName);
        return druidDataSource.getMaxActive();
    }

    public static Integer druidActiveCount(ApplicationContext applicationContext) {
        String[] beanNames = applicationContext.getBeanNamesForType(DruidDataSource.class);

        if (null == beanNames) {
            return -1;
        }

        if (beanNames.length < 1) {
            return -2;
        }

        int activeCount = 0;
        for (String beanName : beanNames) {
            DruidDataSource druidDataSource = (DruidDataSource) applicationContext.getBean(beanName);
            activeCount += druidDataSource.getActiveCount();
        }
        return activeCount;
    }
}